package com.kmxd.ams.app.oss.command;

import cn.hutool.core.util.StrUtil;
import com.kmxd.ams.core.common.constant.ErrorCode;
import com.kmxd.ams.core.common.enums.DbTypeEnum;
import com.kmxd.ams.core.config.AmsConfig;
import com.kmxd.ams.core.exception.BizTipException;
import com.kmxd.ams.infra.system.mapper.SysFondsMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 判断电子文件表是否存在
 *
 * @author zuolg
 */
@Slf4j
@Service
@AllArgsConstructor
public class CheckTableCmd {
  private final SysFondsMapper sysFondsMapper;
  private final AmsConfig amsConfig;

  /**
   * 判断数据库中表是否存在 0 不存在 1 存在
   *
   * @param tableName
   * @return
   */
  public int getTableCount(String tableName) {
    String tableSchema;
    int count = 0;
    if (StrUtil.isBlank(amsConfig.getDbType())) {
      throw BizTipException.instance(ErrorCode.VALIDATE_ERROR, "数据库类型为识别！" + amsConfig.getDbType());
    }
    if (StrUtil.equals(DbTypeEnum.MYSQL.getCode(), amsConfig.getDbType())) {
      tableSchema = sysFondsMapper.getDataBaseId();
      count = sysFondsMapper.haveEfileTable(tableSchema, tableName);
    } else if (StrUtil.equals(DbTypeEnum.PG.getCode(), amsConfig.getDbType())) {
      tableSchema = amsConfig.getDbName();
      count = sysFondsMapper.haveEfileTablePG(tableSchema, tableName);
    } else if (StrUtil.equals(DbTypeEnum.DM.getCode(), amsConfig.getDbType())) {
      tableSchema = amsConfig.getDbName();
      count = sysFondsMapper.haveEfileTableDM(tableSchema, tableName);
    } else {
      throw BizTipException.instance(ErrorCode.VALIDATE_ERROR, "未知的数据库类型！" + amsConfig.getDbType());
    }
    return count;
  }

  /**
   * 判断表名是否存在
   * @param tableSchema
   * @param tableName
   * @return
   */
  public int getTableCount(String tableSchema,String tableName) {
    int count = 0;
    if (StrUtil.isBlank(amsConfig.getDbType())) {
      throw BizTipException.instance(ErrorCode.VALIDATE_ERROR, "数据库类型为识别！" + amsConfig.getDbType());
    }
    if (StrUtil.equals(DbTypeEnum.MYSQL.getCode(), amsConfig.getDbType())) {
      tableSchema = sysFondsMapper.getDataBaseId();
      count = sysFondsMapper.haveEfileTable(tableSchema, tableName);
    } else if (StrUtil.equals(DbTypeEnum.PG.getCode(), amsConfig.getDbType())) {
      tableSchema = amsConfig.getDbName();
      count = sysFondsMapper.haveEfileTablePG(tableSchema, tableName);
    } else if (StrUtil.equals(DbTypeEnum.DM.getCode(), amsConfig.getDbType())) {
      tableSchema = amsConfig.getDbName();
      count = sysFondsMapper.haveEfileTableDM(tableSchema, tableName);
    } else {
      throw BizTipException.instance(ErrorCode.VALIDATE_ERROR, "未知的数据库类型！" + amsConfig.getDbType());
    }
    return count;
  }
}
